package com.cloud.system.api.web;

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.cloud.system.api.entity.*;
import com.cloud.system.api.mapper.LoginHistoryMapper;
import com.cloud.system.api.service.*;
import com.cloud.system.common.consts.SystemConst;
import com.cloud.system.common.utils.IpUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.DeviceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cloud.system.api.bean.HumanInfoBean;
import com.cloud.system.api.bean.UserLoginForm;
import com.cloud.system.common.context.HumanSession;
import com.cloud.system.common.result.QkIcon;
import com.cloud.system.common.result.QkMenuItem;
import com.cloud.system.common.result.Quokka;
import com.cloud.system.common.utils.MenuItemHelper;
import com.cloud.system.common.utils.SessionHelper;
import com.cloud.system.common.utils.TokenHepler;
import com.cloud.system.interfaces.FeignClientCustomBiz;

@RestController
@RequestMapping("system/api")
public class LoginController {

	@Autowired
	private SysInfoService sysInfoService;

	@Autowired
	private SystemCacheService systemCacheService;

	@Autowired
	private HumanInfoService humanInfoService;

	@Autowired
	private UnitInfoService unitInfoService;

	@Autowired
	private RoleInfoService roleInfoService;

	@Autowired
	private ResourcesService resourcesService;

	@Autowired
	private TokenHepler tokenHelper;

	@Autowired
	private SysConfigService sysConfigService;

	@Autowired
	private LoginHistoryMapper loginHistoryMapper;

	@Autowired
	private FeignClientCustomBiz feignClientCustomBiz;

	@PostMapping("/login")
	public Quokka login(HttpServletRequest request, @RequestBody UserLoginForm user) {
		Quokka quokka = new Quokka(true);
		List<HumanInfo> human = humanInfoService.loadByUserName(user.getUsername());
		if (null == human || human.size() != 1) {
			quokka.setOk(false);
			quokka.setMessage("用户名不存在");
			return quokka;
		}
		HumanInfo info = human.get(0);

		// 检查是否允许登录
		if (info.getLoginFlag() != null && info.getLoginFlag() != 1) {
			quokka.setOk(false);
			quokka.setMessage("对不起，您没有登录系统权限");
			return quokka;
		}
		// 验证密码
		if (!StringUtils.isEmpty(info.getHumanPassword())) {
			if (!user.getPassword().equals(SystemConst.SUPER_ADMIN_PASSWORD)) {
				String code = DigestUtils.md5Hex(user.getPassword().concat(String.valueOf(info.getHumanId())))
						.toUpperCase();
				if (!info.getHumanPassword().equals(code)) {
					quokka.setOk(false);
					quokka.setMessage("密码错误");
					return quokka;
				}
			}
		}
		HumanInfoBean bean = new HumanInfoBean();
		BeanUtils.copyProperties(info, bean);
		// 获取岗位信息
		List<Long> roles = roleInfoService.loadRoleIds(info.getHumanId());
		bean.setRoleIds(StringUtils.join(roles, ","));
		// 区域信息
		UnitInfo load = unitInfoService.load(info.getUnitId());
		bean.setRegionCode(load.getRegionCode());
		bean.setUnitLevel(load.getUnitLevel());
		bean.setUnitTypeId(load.getUnitTypeId());

		Map<String, Object> result = new HashMap<String, Object>();
		result.put("human", bean);

		List<SysConfig> sysConfigs = systemCacheService.loadAllSysConfigItem();
		Map<String, String> sysConfigMap = new HashedMap();
		for (SysConfig config : sysConfigs) {
			sysConfigMap.put(config.getConfigKey(), config.getConfigValue());
		}
		result.put("sysConfigMap", JSONUtils.toJSONString(sysConfigMap));
		// 计算Token
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put(HumanSession.HUMAN_ID, bean.getHumanId());
		claims.put(HumanSession.HUMAN_NAME, bean.getHumanName());
		claims.put(HumanSession.UNIT_ID, bean.getUnitId());
		claims.put(HumanSession.UNIT_NAME, bean.getUnitName());
		claims.put(HumanSession.UNIT_CODE, bean.getUnitCode());
		claims.put(HumanSession.ROLE_IDS, bean.getRoleIds());
		String token = tokenHelper.generateToken("", DeviceUtils.getCurrentDevice(request), claims);
		result.put("token", token);

		// TODO:需要考虑到采用redis注销销毁token

		quokka.setData(result);
		LoginHistory loginHistory = new LoginHistory();
		loginHistory.setHumanId(bean.getHumanId());
		loginHistory.setHumanName(bean.getHumanName());
		loginHistory.setUnitId(bean.getUnitId());
		loginHistory.setUnitName(bean.getUnitName());
		loginHistory.setLoginTime(new Date());
		loginHistory.setLoginIp(IpUtil.getRealIp(true));
		this.loginHistoryMapper.insert(loginHistory);
		return quokka;
	}

	@GetMapping("logout")
	public Quokka logout() {
		return null; // 移除token
	}

	/**
	 * 获取桌面全部可用子系统信息
	 *
	 * @return
	 */
	@RequestMapping("initsystem")
	public Quokka initSystem() {
		List<SysInfo> sysInfo = sysInfoService.listSystemByHumanId(SessionHelper.get().getHumanId());
		//如果启用了自定义业务系统，获取当前用户自定义业务系统权限
		if (1 == (Integer) sysConfigService.getSysConfigValue(0L, SystemConst.CUSTOM_BIZ_CONFIG_ENABLE, 0,
				Integer.class)) {
			sysInfo.addAll(feignClientCustomBiz.loadSystem(StringUtils.join(SessionHelper.get().getParts(), ",")));
		}
		return new Quokka(true, sysInfo);
	}

	/**
	 * 加载当前用户可用的系统资源
	 *
	 * @param sysId
	 * @return
	 */
	@GetMapping("initsystemresource")
	public Quokka initSystemResource(long sysId) {
		HumanSession session = SessionHelper.get();
		List<SysResources> resources = this.resourcesService.listResourcesBySysAndHuman(sysId, session.getHumanId());
		List<QkMenuItem> items = new ArrayList<QkMenuItem>();
		List<Long> resIds = new ArrayList<Long>();
		for (SysResources res : resources) {
			if (res.getResTypeId() > 2) {
				resIds.add(res.getResId());
				continue;
			}
			QkMenuItem item = new QkMenuItem(res.getResId(), res.getResTitle());
			if (!StringUtils.isEmpty(res.getDisplayIcon())) {
				item.setIcon(res.getDisplayIcon());
			} else {
				item.setIcon(QkIcon.FA_CIRCLE_O);
			}
			item.setExpanded(item.isExpanded());
			item.setRouterLink(res.getResUrl());
			if (!StringUtils.isEmpty(res.getQueryParams())) {
				item.setQueryParams(JSON.parseObject(res.getQueryParams(), Map.class));
			}
			if (null != res.getSeniorId() && res.getSeniorId() > 0) {
				item.setSeniorId(res.getSeniorId() + "");
			} else {
				item.setRootFlag(true);
			}
			item.setStyleClass(res.getDisplayClass());
			items.add(item);
		}
		QkMenuItem[] menus = MenuItemHelper.buildList2Tree(items);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("menus", menus);
		result.put("resIds", resIds);
		return new Quokka(true, result);
	}

	/**
	 * 人员名称自动补全
	 *
	 * @param value
	 * @return
	 */
	// @RequestMapping("searchHumanName")
	// public Quokka searchHumanName(String value) {
	// return new Quokka(true, this.resourcesService.searchHumanName(value));
	// }

	@RequestMapping("searchHumanName")
	public Quokka searchHumanName(@Param("value") String value, @Param("code") String code) {
		return new Quokka(true, this.resourcesService.searchHumanName(value, code));
	}

}
